package com.itheima52.mobilesafe.service;

import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.TextView;

/**
 * 获取经纬度的服务
 * 
 * @author ludaxu
 * 
 */
public class LocationService extends Service {
	private LocationManager lm;
	private MyLocationListener listener;
	private SharedPreferences mPref;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mPref = getSharedPreferences("config", MODE_PRIVATE);
		lm = (LocationManager) getSystemService(LOCATION_SERVICE);
		List<String> allProviders = lm.getAllProviders();// 获取所有的位置提供者,也就是定位方式
		System.out.println(allProviders);
		Criteria criteria = new Criteria();
		criteria.setCostAllowed(true);// 是否允许付费,比如3g,4g网络定位
		criteria.setAccuracy(Criteria.ACCURACY_FINE);// 精确度(越高,耗电越大)
		// 1.criteria标准:2.是BestProvider,true,可用返回,false,可不可用都返回
		String bestProvider = lm.getBestProvider(criteria, true);// 获取最佳的提供者
		listener = new MyLocationListener();
		// 定位方式,最短的更新时间(s),最短的更新距离(m),监听
		lm.requestLocationUpdates(bestProvider, 0, 0, listener);

	}

	class MyLocationListener implements LocationListener {

		// 位置发生改变
		@Override
		public void onLocationChanged(Location location) {
			double longitude = location.getLongitude();// 经度
			double latitude = location.getLatitude();// 纬度
			double altitude = location.getAltitude();// 海拔.不稳定,有时拿的到,有时拿不到
			float accuracy = location.getAccuracy();// 精确度
			// 将获取的经纬度保存在sharepreference中
			mPref.edit()
					.putString("location", "经度:" + longitude + "纬度:" + latitude)
					.commit();
			stopSelf();// 停掉自己的service

		}

		// 用户关闭GPS
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		// 用户打开GPS
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		// 位置提供者的状态发生变化,比如是信号的原因无法接收信号
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		lm.removeUpdates(listener);// 当activity销毁时,关闭监听服务
	}

}
